package com.guoliang.ucenterService.controller;

import com.google.gson.Gson;
import com.guoliang.commonUtils.JwtUtils;
import com.guoliang.service.exceptionHandler.MyException;
import com.guoliang.ucenterService.entity.UcenterMember;
import com.guoliang.ucenterService.service.UcenterMemberService;
import com.guoliang.ucenterService.utils.ConstantWXUtils;
import com.guoliang.ucenterService.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author ：Leo
 * @date ：Created in 2023/1/28 12:51
 * @description：
 */
@Controller
@RequestMapping("/api/ucenter/wx")
public class WXAPiController {
    @Autowired
    private UcenterMemberService memberService;
    //生成二维码
    @GetMapping("login")
    public String getWxCode(){
        String baseUrl= "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        //对url进行编码
        String redirectUrl=ConstantWXUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl=URLEncoder.encode(redirectUrl,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        baseUrl=String.format(baseUrl
                ,ConstantWXUtils.WX_OPEN_APP_ID
                ,redirectUrl
                ,"atguigu");
        return "redirect:"+baseUrl;
    }
    @GetMapping("callback")
    public String callback(@RequestParam String code, @RequestParam String state){
        //获取access_token
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +"?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        String accessTokenUrl = String.format(baseAccessTokenUrl,
                ConstantWXUtils.WX_OPEN_APP_ID,
                ConstantWXUtils.WX_OPEN_APP_SECRET,
                code);
        try {
            String token = HttpClientUtils.get(accessTokenUrl);
            Gson gson=new Gson();
            HashMap mapAccessToken = gson.fromJson(token, HashMap.class);
            String accessToken = (String) mapAccessToken.get("access_token");
            String openid = (String) mapAccessToken.get("openid");
            //通过得到的access_token获取用户信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
            String userInfo = HttpClientUtils.get(userInfoUrl);
            HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
            //获取到扫码人昵称和头像
            String nickname = (String)userInfoMap.get("nickname");
            String headimgurl = (String) userInfoMap.get("headimgurl");
            UcenterMember member=memberService.getMemberByOpenId(openid);
            if (member==null){
                //数据库不存在该用户
                member = new UcenterMember();
                member.setNickname(nickname);
                member.setOpenid(openid);
                member.setAvatar(headimgurl);
                memberService.save(member);

            }
            //使用JWT生成token
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            return "redirect:http://localhost:3000?token="+jwtToken;
        } catch (Exception e) {
            throw new MyException(20001,"登陆失败");
        }


    }
}
